package com.example.springboot;

import com.example.springboot.highligter.HighlightUtil;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;

import java.io.IOException;

/**
 * Created by tangmayao on 2018/4/4.
 */
public class TestHighlight {

    private String[] fragments=new String[]{
        "think in java",
            "java入门"
    };

    @Test
    public  void  test(){
        HighlightUtil highlightUtil=new HighlightUtil();

        Directory directory=new RAMDirectory();
        Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_CURRENT);
        IndexWriterConfig writerConfig=new IndexWriterConfig(Version.LUCENE_CURRENT,analyzer);
        try {
            IndexWriter indexWriter=new IndexWriter(directory,writerConfig);

            for(String fragment:fragments){
                Document document=new Document();
                document.add(new TextField("title",fragment, Field.Store.YES));
                indexWriter.addDocument(document);
            }

            indexWriter.close();

            IndexReader indexReader= DirectoryReader.open(directory);
            IndexSearcher indexSearcher=new IndexSearcher(indexReader);
            QueryParser queryParser=new QueryParser(Version.LUCENE_CURRENT,"title",analyzer);
            Query query=queryParser.parse("java");
            TopDocs tds = indexSearcher.search(query,10);


            for(ScoreDoc sd :tds.scoreDocs){
                Document doc = indexSearcher.doc(sd.doc);
                String title = doc.get("title");
                title = highlightUtil.highlightStr(query, analyzer, "title", title);
                System.out.println(title);
            }


        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }


    }
}